import ajax from '@/api'
import { urlHandler } from 'utils/helper/url-handler'
import { CHANNEL, getChannel } from 'utils/config'
import UA from 'utils/ua'
import storage from 'utils/helper/storage'
// https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115  微信公众号 API
let wxObj
const ticketRule = new RegExp(`&?ticket=[\\w-%]+`, 'gi')

export const setWxconfig = (url, params, callback) => {
  if (!UA.isWxWebview) return
  // params = newWxParse(params)

  if (wxObj) {
    setWxApi.call(this, url, params, callback)
    return
  }
  return new Promise((resolve, reject) => {
    let wxjs = 'https://res2.wx.qq.com/open/js/jweixin-1.4.0.js'
    let wxScript = document.createElement('script')
    wxScript.src = wxjs
    wxScript.onload = function() {
      wxObj = wx
      setWxApi.call(this, url, params, callback)
    }
    document.body.appendChild(wxScript)
  })
}

/**
 * 设置微信jssdk
 * @param {*} url 
 * @param {*} params [{api: arguments]}]
 * @param {*} callback 
 */
function setWxApi(url, params, callback) {
  // let href = location.href && location.href.split('#')[0]
  getWxconfig({
    // url:
    //   system == 'ios'
    //     ? encodeURIComponent(window.entryUrl)
    //     : encodeURIComponent(href),
    url: encodeURIComponent(url),
    wechatType: getChannel()
  }).then(
    res => {
      if (res.data.code == 100) {
        let result = res.data.data
        wx.config({
          debug: false,
          appId: result.appId, // 必填，公众号的唯一标识
          timestamp: result.timestamp, // 必填，生成签名的时间戳
          nonceStr: result.noncestr, // 必填，生成签名的随机串
          signature: result.signature, // 必填，签名，见附录1
          jsApiList: Object.keys(params)
        })

        wx.ready(function() {
          console.log('*********微信ready***********')
          // console.log(params)
          for (let apiKey in params) {
            if (params[apiKey]) {
              wx[apiKey](params[apiKey])
            }
          }
          callback && callback()
        })
        wx.error(function(res) {})
      } else {
        throw new Error(res.data.message)
      }
    },
    function() {}
  )
}

export const getWxconfig = params => {
  return ajax.get('/gate-login/wechatConfig', { params })
}

// url有新公众号带参 则给分享链接加上
function newWxParse(params) {
  if (!params) {
    return params
  }
  for (let apiKey in params) {
    if (
      [
        'onMenuShareAppMessage',
        'onMenuShareTimeline',
        'updateAppMessageShareData',
        'updateTimelineShareData'
      ].indexOf(apiKey) > -1
    ) {
      if (params[apiKey] && params[apiKey].link) {
        params[apiKey].link = urlHandler.outLinkParse(params[apiKey].link)
      }
    }
  }
  return params
}

// weixin登录相关
// 先去拿ticket，(请求接口，接口返回带ticket字段的当前url后，重新加载页面)
export const callWxLogin = path => {
  let url = null
  if (path) {
    url = path
  } else {
    url = location.href
  }
  let urlObj = null
  let routerParam = null
  let domain = ''
  let href = ''
  let redirectUrl = ''
  // 重定向网关-->会员接口-->微信接口获取ticket
  urlObj = urlHandler.parseURL(url)
  routerParam = urlObj.hash.replace(ticketRule, '')
  domain = url.split('#')[0].split('?')[0]
  // 传参&转码，助于接口返回后&拼接的参数不会丢失
  href = domain + urlObj.query.replace(/\&/gi, '%26') + '#' + routerParam
  redirectUrl = `/gate-login/authorize?wechatType=${CHANNEL}&redirect=${href}`
  sdk.showToast({
    title: '您尚未登录，正在自动登录中...'
  })
  location.replace(redirectUrl)
}

// url带ticket后调网关接口换取token
export const wxCheckUrlTicket = () => {
  let url = location.href
  let ticketStr, ticket
  ticketStr = url.match(ticketRule)
  ticket = ticketStr && ticketStr[ticketStr.length - 1].toString().split('=')[1]
  return new Promise((resolve, reject) => {
    if (ticket) {
      let params = { CHANNEL: CHANNEL, ticket: ticket }
      ajax.get('/gate-login/getWxToken', { params }).then(
        response => {
          if (response.data.code == 100) {
            // “AUTHORIZATION”和游必得存储字段保持一致
            storage.set('AUTHORIZATION', response.data.data)
          }
          clearUrlTicket()
          resolve(true)
        }
      ).catch((err) => {
        clearUrlTicket()
        resolve(true)
      })
    } else {
      resolve(false)
    }
  })
}

// 清除url中的ticket信息
function clearUrlTicket() {
  let current = window.location.href
  current = removeTicket(current)
  window.history.replaceState(null, document.title, current)
  
  // // 仍然不行则多加一层历史记录
  if (ticketRule.test(location.href)) {
    window.location.href = location.href.replace(ticketRule, '')
  }
}

const removeTicket = url => {
  // 剔除ticket
  url = decodeURIComponent(url)
  url = url.replace(ticketRule, '')
  // 剔除多余#号
  url = (url.indexOf('#') > 0 && url.split('#')[0]) || url
  return url
}


export default callWxLogin
